package com.freedom.rpc.thrift.client;

import org.apache.thrift.protocol.TMultiplexedProtocol;
import com.freedom.rpc.thrift.common.extended.ServiceNameFieldHelper;
import com.freedom.rpc.thrift.common.machine.MachineResource;
import com.freedom.rpc.thrift.common.socket.TSocketPool;
import com.freedom.rpc.thrift.common.utils.Logger;
import com.freedom.rpc.thrift.common.utils.SocketUtils;
import com.freedom.rpc.thrift.common.utils.StringUtils;
import com.freedom.rpc.thrift.common.utils.TimeUtils;
import com.freedom.rpc.thrift.common.zookeeper.client.ClientSideZkReadyListener;
import com.freedom.rpc.thrift.service.HelloWorldService;

public class MyClient {

	private static final Logger logger = Logger.getLogger(MyClient.class);
	static {
		// 必须调用，等待zk准备好!!!
		ClientSideZkReadyListener.ready();
	}

	public static void main(String[] args) {
		// int count = 1;
		// while (count-- >= 0) {
		new Thread(new Runnable() {
			@Override
			public void run() {
				while (true) {
					try {
						test();
					} catch (Exception e) {
						e.printStackTrace();
					} finally {
						TimeUtils.sleep(3000);
					}
				}
			}

		}).start();
		//
		// }

	}

	public static void test() throws Exception {
		// 测试代码
		String group = "test";
		String service = "HelloWorldService";
		String groupWithService = StringUtils.groupUnionService(group, service);
		TSocketPool pool = MachineResource.getInstance().getSocketPool(groupWithService);// pool
		if (null == pool) {
			throw new Exception("fail to fetch socket pool...");
		}
		TMultiplexedProtocol tMultiProtocol = pool.borrowObject();// tMultiProtocol
		if (null == tMultiProtocol) {
			throw new Exception("fail to fetch a socket from pool...");
		}
		try {
			ServiceNameFieldHelper.set(tMultiProtocol, service);// 注入本次的服务名
			HelloWorldService.Client client = new HelloWorldService.Client(tMultiProtocol);
			logger.info("client.helloWorldBoolean()---" + client.helloWorldBoolean(3));// 调用时注意只调用自己定义的接口方法，其它不要调用，以免出错]
		} catch (Exception e) {
			SocketUtils.setAlive(tMultiProtocol, false, e);// 通过业务侧，我们也做了连接可用性的探测
			throw e;
		} finally {
			pool.returnObject(tMultiProtocol);
		}
	}
}
